package com.demo.controller;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;

import com.demo.common.constant.DictKeys;
import com.demo.common.model.AuthUser;
import com.demo.common.model.LoginLog;
import com.demo.service.LoginService;
import com.demo.tools.ToolUtils;
import com.demo.tools.ToolWeb;
import com.demo.validator.LoginValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

public class LoginController  extends Controller {
	
	public void index(){
		String username = getPara("username");
		String password = getPara("password");
		LoginLog loginLog = new LoginLog();
		AuthUser user = AuthUser.me.login(username, DigestUtils.md5Hex(password));
		//int a = LoginService.service.login(username,password);
		Date date = new Date();
		String ip = ToolWeb.getIpAddr(getRequest());
		loginLog.set("id", ToolUtils.getUuidByJdk(true));
		loginLog.set("user_name", username);
		loginLog.set("ip", ip);
		loginLog.set("method", getRequest().getMethod());
		loginLog.set("login_date", date);
		if(user!=null){
			setSessionAttr(DictKeys.SESSION_ADMIN_USER, user);
			user.set("last_login", date)
				.set("last_loginip", ip)
				.set("login_times",user.getLoginTimes()==null?1:user.getLoginTimes()+1).
				update();
			loginLog.set("status", true);
			loginLog.set("user_id", user.getId());
			redirect("/admin/index");
		}else{
			setAttr("Msg", "用户名或密码错误！");
			loginLog.set("status", false);
			render("/admin/login.html");

		}
		loginLog.save();
	}
	@Before(LoginValidator.class)
	public void login(){
		String username = getPara("username");
		String password = getPara("password");
		AuthUser user = AuthUser.me.login(username, DigestUtils.md5Hex(password));
		//int a = LoginService.service.login(username,password);
		if(user!=null){
			setSessionAttr(DictKeys.SESSION_ADMIN_USER, user);
			user.set("last_login", new Date()).update();
			redirect("/admin/index");
			return ;
		}else{
			setAttr("Msg", "用户名或密码错误！");
			render("/admin/login.html");

		}
	}
	//注销
	public void logout(){
		removeSessionAttr(DictKeys.SESSION_ADMIN_USER);
		render("/admin/login.html");
	}

}
